package com.channel.base;

import com.cloud.base.bean.OpenConfig;
import com.cloud.base.proxy.ApiFactory;
import com.cloud.base.proxy.RequestHandler;

import com.channel.wxpublic.token.AccessTokenData;
import com.channel.wxpublic.token.AccessTokenParam;
import com.channel.wxpublic.token.WxMpAccessToken;
import com.common.utils.tools.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component()
public class WxChatService implements RequestHandler {
    @Override
    public Map<String, String> buildRequestParam(Map<String, String> param, OpenConfig config) {
        String accessToken = getAccessToken(config);
        param.put("access_token", accessToken);
        return param;
    }

    @Override
    public String getSign(Map<String, String> param, String key) {
        return null;
    }

    @Override
    public Map<String, String> buildPayParam(Map<String, String> param, OpenConfig config) throws Exception {
        return null;
    }

    public String getAccessToken(OpenConfig config) {
        WxMpAccessToken wxMpAccessToken = ApiFactory.create(WxMpAccessToken.class, config);
        AccessTokenParam accessTokenParam = new AccessTokenParam();
        accessTokenParam.setAppid(config.getAppId());
        accessTokenParam.setSecret(config.getSecret());
        AccessTokenData accessToken = wxMpAccessToken.getAccessToken(accessTokenParam);
        if(accessToken == null){
            throw new BusinessException("wxchat internet error");
        }
        if (StringUtils.isEmpty(accessToken.getAccess_token())) {
            throw new BusinessException("wxchat error code:" + accessToken.getErrcode() + " error msg:" + accessToken.getErrmsg());
        }
        return accessToken.getAccess_token();
    }
}
